package io.renren.utils.util;

import java.util.Locale;

import org.apache.log4j.Logger;

import io.renren.utils.util.exception.XMTException;

public class CommonErrorUtil {
	static Logger logger = Logger.getLogger(CommonErrorUtil.class.getName());

	public static Error getError(int code) {
		return Error.errorMap.get(code);
	}
	
	public static String getErrorLocalizedMessage(Error error) {
		return getErrorLocalizedMessage(error, null, new Object[]{""});
	}
	
	public static String getErrorLocalizedMessage(Error error, Locale locale, Object [] parms) {
		String errorMsgKey = error.getErrorMessage();
		return MessageResourceUtil.getMessage(locale, errorMsgKey, parms);
	}
	public static String getErrorLocalizedMessage(Exception e) {
		return getErrorEventMessage(e, null, new Object[]{e.getMessage()});
	}

	public static String getErrorEventMessage(Exception e, Locale locale, Object [] parms) {
		String message = e.getMessage();
		if (e instanceof XMTException) {
			int code = ((XMTException) e).getCauseCode();
			if (code!=0) {
				Error error = getError(code);
				if (error!=null) {
					message = getErrorLocalizedMessage(error, locale, parms);
				}
			}
		} else {
			message = MessageResourceUtil.getMessage(locale, message);
		}
		if (message==null) {
			message = e.getMessage();
		}
		
		return message;
	}

    public static void main (String[] args) {
    	try {
    		Exception e = new XMTException("TTT", 10001);
    		Object [] parms_zh = new Object[]{"壹贰叁", "标题", "消息", "参数"};
    		
    		System.out.println(CommonErrorUtil.getErrorLocalizedMessage(e));
    		
    		System.out.println(CommonErrorUtil.getErrorEventMessage(e,null,parms_zh ));
    		
    	} catch (Exception ex) {
    		ex.printStackTrace();
    	}
    }
}
